package com.lanyou.esb.entity;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.lanyou.cook.common.Constants;
import com.lanyou.cook.common.DefaultDateJsonSerializer;
import com.lanyou.cook.entity.domain.FieldSystem;
import com.lanyou.cook.repository.FieldSystemRepository;
import com.lanyou.cook.service.ApplicationContextKeeper;
import com.lanyou.esb.datadictionary.AuditStatusType;
import com.lanyou.esb.datadictionary.IfType;
import com.lanyou.esb.repository.HttpRepository;

/**
 * 
 * @author ly-zengzugen
 *
 */


@Entity
@EntityListeners({ AuditingEntityListener.class })
@Table(name = "T_ESB_BU_IF_HTTP")
// 还没有增加监听
public class Http {

	private String id;// http表接口ID

	private String systemCode;// 系统编码

	private String name;// 接口名称

	private String code;// 接口编码

	private String bundleType;// BUNDLE模式

	private String ifPublic;// 是否公开

	private String authType;// 认证方式
	
	private String contentType;//文本类型

	private String type;// 接口类型

	private String desc;// 接口描述

	private String priUrl;// 接口原始地址

	private String pubUrl;// 接口发布地址

	private String version;// 接口版本

	private String status;// 接口状态

	private String request;// 接口请求的方法
	
	private String operationType;//接口操作类型
	
	
	private String transportProtocol;//接口传输协议(http、https)

	private String dataFormate;// 数据格式

	private String overtime;// 超时时长

	private String ifCost;// 是否收费

	private String remark;// 备注

	private String auditStatus;// 审核状态

	private String auditRemark;// 审核意见

	private String requestMess;// 请求参数报文

	private String returnMess;// 返回参数报文

	private String ifOlation;// 是否隔离
	
	private String isTrace;
	
	private String soapActionUri;
	
	private String isEnable;

	private String creator;

	private String modifier;

	private Date createTime;

	private Date modifyTime;

	private FieldSystem fieldSystem;
	
	private Set<DefinedBundle> definedbundles = new HashSet<DefinedBundle>();

	private Set<Token> interfaceToken;
	
	private Set<IfParameter> interfaceParameter;
	
	private Set<IfReqQuantity> interfaceRequestQuantity = new HashSet<IfReqQuantity>();
 
	private Set<FieldSystem> visibleFieldSystems = new HashSet<FieldSystem>();
	
	//private InterfaceRequestQuantity requestQuantity;
	
	private int requestNum;
	
	public final static Specification<Http> EmptySpecification = new Specification<Http>(){
		@Override
		public Predicate toPredicate(Root<Http> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
			return null;
		}
	};
	
	public static Specification<Http> idSpecification(String id){
		return new Specification<Http>(){
			@Override
			public Predicate toPredicate(Root<Http> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				query.where(cb.equal(root.get("id"), id));
				return null;
			}
		};
	}
	
	
	@Id
	@GeneratedValue(generator = "uuidGenerator")
	@GenericGenerator(name = "uuidGenerator", strategy = "uuid")
	@Column(name = "IF_HTTP_ID", length = 36)
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	@Column(name = "SYSTEM_CODE", length = 50)
	public String getSystemCode() {
		return systemCode;
	}
	
	@Column(name="IS_TRACE")
	public String getIsTrace() {
		return isTrace;
	}


	public void setIsTrace(String isTrace) {
		this.isTrace = isTrace;
	}
	
	public void setSystemCode(String systemCode) {
		this.systemCode = systemCode;
	}

	@Column(name = "IF_NAME", length = 50)
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Column(name = "IF_CODE", length = 50)
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	@Column(name = "BUNDLE_TYPE", length = 2)
	public String getBundleType() {
		return bundleType;
	}

	public void setBundleType(String bundleType) {
		this.bundleType = bundleType;
	}

	@Column(name = "IS_PUBLIC", length = 2)
	public String getIfPublic() {
		return ifPublic;
	}

	public void setIfPublic(String ifPublic) {
		this.ifPublic = ifPublic;
	}

	@Column(name = "AUTH_TYPE", length = 2)
	public String getAuthType() {
		return authType;
	}

	public void setAuthType(String authType) {
		this.authType = authType;
	}

	@Column(name = "IF_TYPE", length = 2)
	public String getType() {
		return type;
	}
	
	public String getContentType() {
		return contentType;
	}

	@Column(name = "CONTENT_TYPE", length = 2)
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public void setType(String type) {
		this.type = type;
	}

	@Column(name = "IF_DESC", length = 1000)
	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	@Column(name = "IF_PRI_URL", length = 100)
	public String getPriUrl() {
		return priUrl;
	}

	public void setPriUrl(String priUrl) {
		this.priUrl = priUrl;
	}

	@Column(name = "IF_PUB_URL", length = 100)
	public String getPubUrl() {
		return pubUrl;
	}

	public void setPubUrl(String pubUrl) {
		this.pubUrl = pubUrl;
	}

	@Column(name = "IF_VERSION", length = 10)
	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	@Column(name = "IF_STATUS", length = 2)
	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	@Column(name = "IF_REQUEST", length = 2)
	public String getRequest() {
		return request;
	}

	public void setRequest(String request) {
		this.request = request;
	}

	@Column(name = "IF_OPERATE_TYPE", length = 2)
	public String getOperationType() {
		return operationType;
	}


	public void setOperationType(String operationType) {
		this.operationType = operationType;
	}

	@Column(name = "TRANSPORT_PROTOCOL", length = 2)
	public String getTransportProtocol() {
		return transportProtocol;
	}


	public void setTransportProtocol(String transportProtocol) {
		this.transportProtocol = transportProtocol;
	}


	@Column(name = "DATA_FORMATE", length = 2)
	public String getDataFormate() {
		return dataFormate;
	}

	public void setDataFormate(String dataFormate) {
		this.dataFormate = dataFormate;
	}

	@Column(name = "OVERTIME_TIMES", length = 10)
	public String getOvertime() {
		return overtime;
	}

	public void setOvertime(String overtime) {
		this.overtime = overtime;
	}

	@Column(name = "IS_COST", length = 2)
	public String getIfCost() {
		return ifCost;
	}

	public void setIfCost(String ifCost) {
		this.ifCost = ifCost;
	}

	@Column(name = "REMARK", length = 100)
	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	@Column(name = "AUDIT_STATUS", length = 2)
	public String getAuditStatus() {
		return auditStatus;
	}

	public void setAuditStatus(String auditStatus) {
		this.auditStatus = auditStatus;
	}

	@Column(name = "AUDIT_REMARK", length = 500)
	public String getAuditRemark() {
		return auditRemark;
	}

	public void setAuditRemark(String auditRemark) {
		this.auditRemark = auditRemark;
	}

	@Column(name = "REQUEST_PARA_MESS", length = 1000)
	public String getRequestMess() {
		return requestMess;
	}

	public void setRequestMess(String requestMess) {
		this.requestMess = requestMess;
	}

	@Column(name = "RETURN_PARA_MESS", length = 1000)
	public String getReturnMess() {
		return returnMess;
	}

	public void setReturnMess(String returnMess) {
		this.returnMess = returnMess;
	}

	@Column(name = "IS_ISOLATION", length = 2)
	public String getIfOlation() {
		return ifOlation;
	}

	public void setIfOlation(String ifOlation) {
		this.ifOlation = ifOlation;
	}
	
	@Column(name = "SOAP_ACTION_URI", length = 100)
	public String getSoapActionUri() {
		return soapActionUri;
	}


	public void setSoapActionUri(String soapActionUri) {
		this.soapActionUri = soapActionUri;
	}
	
	@Column(name = "IS_ENABLE", length = 2)
	public String getIsEnable() {
		return isEnable;
	}

	public void setIsEnable(String isEnable) {
		this.isEnable = isEnable;
	}

	@CreatedBy
	@Column(length = 50, updatable = false)
	public String getCreator() {
		return creator;
	}

	public void setCreator(String creator) {
		this.creator = creator;
	}

	@LastModifiedBy
	@Column(length = 50)
	public String getModifier() {
		return modifier;
	}

	public void setModifier(String modifier) {
		this.modifier = modifier;
	}

	@Column(name = "CREATED_DATE", updatable = false)
	@JsonSerialize(using = DefaultDateJsonSerializer.class)
	@CreatedDate
	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	@Column(name = "LAST_UPDATED_DATE")
	@JsonSerialize(using = DefaultDateJsonSerializer.class)
	@LastModifiedDate
	public Date getModifyTime() {
		return modifyTime;
	}

	public void setModifyTime(Date modifyTime) {
		this.modifyTime = modifyTime;
	}

	@ManyToOne
	@JoinColumn(name = "FIELD_SYSTEM_ID")
	public FieldSystem getFieldSystem() {
		return fieldSystem;
	}

	public void setFieldSystem(FieldSystem fieldSystem) {
		this.fieldSystem = fieldSystem;
	}

	@OneToMany(fetch = FetchType.LAZY, mappedBy = "http")
	@JsonIgnore
	public Set<Token> getInterfaceToken() {
		return interfaceToken;
	}

	public void setInterfaceToken(Set<Token> interfaceToken) {
		this.interfaceToken = interfaceToken;
	}
	
	@OneToMany(fetch = FetchType.LAZY, mappedBy = "http")
	@JsonIgnore
	public Set<IfParameter> getInterfaceParameter() {
		return interfaceParameter;
	}

	public void setInterfaceParameter(Set<IfParameter> interfaceParameter) {
		this.interfaceParameter = interfaceParameter;
	}
	
	
	@OneToMany(fetch = FetchType.LAZY, mappedBy = "http")
	@JsonIgnore
	public Set<IfReqQuantity> getInterfaceRequestQuantity() {
		return interfaceRequestQuantity;
	}

	public void setInterfaceRequestQuantity(Set<IfReqQuantity> interfaceRequestQuantity) {
		this.interfaceRequestQuantity = interfaceRequestQuantity;
	}

	@ManyToMany
	@JoinTable(name = "T_ESB_BU_IF_VISIBLITY", 
		joinColumns = @JoinColumn(name = "IF_ID", referencedColumnName = "IF_HTTP_ID") , 
			inverseJoinColumns = @JoinColumn(name = "IF_VISIBLE_SYSTEM_ID", referencedColumnName = "FIELD_SYSTEM_ID") 
	)
	public Set<FieldSystem> getVisibleFieldSystems() {
		return visibleFieldSystems;
	}



	public void setVisibleFieldSystems(Set<FieldSystem> visibleFieldSystems) {
		this.visibleFieldSystems = visibleFieldSystems;
	}
	

	@ManyToMany
	@JoinTable(name = "T_ESB_BU_IF_BUNDLES_RELATION", 
		joinColumns = @JoinColumn(name = "IF_ID", referencedColumnName = "IF_HTTP_ID") , 
			inverseJoinColumns = @JoinColumn(name = "BUNDLE_ID", referencedColumnName = "BUNDLE_ID") 
	)
	public Set<DefinedBundle> getDefinedbundles() {
		return definedbundles;
	}

	public void setDefinedbundles(Set<DefinedBundle> definedbundles) {
		this.definedbundles = definedbundles;
	}


	@Transient
	public String getFieldId() {
		try {
			return (String) PropertyUtils.getProperty(fieldSystem, "field.id");
		} catch (Exception e) {
			return null;
		}
	}
	
	


	@Transient
	public String getFieldName() {
		try {
			return (String) PropertyUtils.getProperty(fieldSystem, "field.name");
		} catch (Exception e) {
			return null;
		}
	}
	
	
	
	@Transient
	public String getFieldSystemId() {
		try {
			return (String) PropertyUtils.getProperty(fieldSystem, "id");
		} catch (Exception e) {
			return null;
		}
	}
	
	
	@Transient
	public String getFieldSystemName() {
		try {
			return (String) PropertyUtils.getProperty(fieldSystem, "name");
		} catch (Exception e) {
			return null;
		}
	}

	@Transient
	public String getIfTypeForDisplay() {
		if(StringUtils.equals(type, IfType.WS.ValueCode)){
			return Constants.WEBSERVICE;
		}else if(StringUtils.equals(type, IfType.REST.ValueCode)){
			return Constants.REST;
		}else if(StringUtils.equals(type, IfType.FTP.ValueCode)){
			return Constants.FTP;
		}else{
			return "";
		}
		
	}
	
	@Transient
	public String getIfAuditStatusForDisplay() {
		if(StringUtils.equals(auditStatus, AuditStatusType.AUDITED.ValueCode)){
			return Constants.AUDITED;
		}else if(StringUtils.equals(auditStatus, AuditStatusType.UNAUDITED.ValueCode)){
			return Constants.UNAUDITED;
		}else{
			return "";
		}
		
	}
	
	public void addParameter(IfParameter parameter) {
		if(parameter==null){
			return;
		}
		if(interfaceParameter==null){
			interfaceParameter=new HashSet<>();
		}
		interfaceParameter.add(parameter);
	}
	
	@Transient
	public int getRequestNum(){
		return requestNum;
	}


	public void setRequestNum(int requestNum) {
		this.requestNum = requestNum;
	}


	@Transient
	public String getCreateTimeForExport(){
		if(createTime != null){
			return createTime.toString().substring(0, createTime.toString().length() - 2);
		}else{
			return "";
		}
		
	}
	
	@Transient
	public String getModifyTimeForExport(){
		if(modifyTime != null){
			return modifyTime.toString().substring(0, modifyTime.toString().length() - 2);
		}else{
			return "";
		}
	}

}